//
// Created by denglibin on 19-10-24.
//
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>
#include<errno.h>
#include <arpa/inet.h>
static const int  port = 8888;
void start(char * server_ip){
    int sock_fd;
    char sendbuf[1024], recvbuf[1024];
    struct sockaddr_in server_addr;//服务端地址
    //初始化socket
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(sock_fd == -1){
        printf("%s\n",strerror(errno));
        return;
    }
    //编辑服务端地址信息
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    inet_pton(AF_INET, server_ip, &server_addr.sin_addr.s_addr); // 设置服务端的ip
    //连接服务端socket
    int tmp = connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
    if(tmp == -1){
        printf("%s\n",strerror(errno));
        return;
    }
    printf("Connect success, now you can send msg;  Enter 'q' to quit!\n");
    while(1){
        fgets(sendbuf, sizeof(sendbuf), stdin);
        if(sendbuf[0] == 'q' ){
            break;
        }
        send(sock_fd, sendbuf, strlen(sendbuf), 0);
        recv(sock_fd, recvbuf, sizeof(recvbuf), 0);
        printf("%s", recvbuf);
        memset(sendbuf, 0, sizeof(sendbuf));
        memset(recvbuf, 0, sizeof(recvbuf));
    }
    close(sock_fd);
}
static int main_(int argc, char * argv[]){

    start(argv[1]);
    return 0;
}


